import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import axios from 'axios'
import pako from 'pako'

Vue.use(VueRouter)

axios.defaults.baseURL = ''

const routes = [
  {
    path: '/',
    redirect: '/user/login'
  },
  {
    path: '/user/login',
    name: 'login',
    component: () => import('../views/user/login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/user/register',
    name: 'register',
    component: () => import('../views/user/register.vue'),
    meta: {
      title: '注册'
    }
  },
  {
    path: '/user',
    component: () => import('../views/user.vue'),
    children: [
      {
        path: '',
        redirect: 'home'
      },
      {
        path: 'home',
        name: 'user_home',
        component: () => import('../views/user/home.vue'),
        meta: {
          title: '主页'
        }
      },
      {
        path: 'animal',
        name: 'animal',
        component: () => import('../views/user/animal.vue'),
        meta: {
          title: '牲畜管理'
        }
      },
      {
        path: 'proc',
        name: 'proc',
        component: () => import('../views/user/proc.vue'),
        meta: {
          title: '加工登记'
        }
      },
      {
        path: 'order',
        name: 'order',
        component: () => import('../views/user/order.vue'),
        meta: {
          title: '订单管理'
        }
      },
      {
        path: 'stock',
        name: 'stock',
        component: () => import('../views/user/stock.vue'),
        meta: {
          title: '上架管理'
        }
      },
      {
        path: 'emp',
        name: 'emp',
        component: () => import('../views/user/emp.vue'),
        meta: {
          title: '员工管理'
        }
      },
      {
        path: 'lic',
        name: 'lic',
        component: () => import('../views/user/lic.vue'),
        meta: {
          title: '备案管理'
        }
      },
      {
        path: 'prof',
        name: 'prof',
        component: () => import('../views/user/prof.vue'),
        meta: {
          title: '修改信息'
        }
      }
    ]
  },
  {
    path: '/admin/login',
    component: () => import('../views/admin/login.vue'),
    name: 'admin_login',
    meta: {
      title: '管理员登录'
    }
  },
  {
    path: '/admin',
    component: () => import('../views/admin.vue'),
    children: [
      {
        path: '',
        redirect: '/home'
      },
      {
        path: 'home',
        name: 'admin_home',
        component: () => import('../views/admin/home.vue'),
        meta: {
          title: '主页'
        }
      },
      {
        path: 'accInquiry',
        name: 'accInquiry',
        component: () => import('../views/admin/accInquiry.vue'),
        meta: {
          title: '账号查询管理'
        }
      },
      {
        path: 'record',
        name: 'record',
        component: () => import('../views/admin/record.vue'),
        meta: {
          title: '备案管理'
        }
      }
    ]
  },
  {
    path: '/trace/:hash',
    name: 'trace',
    component: () => import('../views/trace.vue'),
    props: true
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404.vue'),
    meta: {
      title: '404'
    }
  },
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path.startsWith('/public')) {
    next()
  } else if (to.path.startsWith('/admin')) {
    next()
  } else if (to.path.startsWith('/user')) {
    const token = localStorage.getItem('trace-token')

    if (to.path === '/user/login' || to.path === '/user/register') {
      if (token === null || token === '') {
        next()
      } else {
      // 如果已有 token 且正确则跳转到主页
        axios.get('/api/ent/detail', {
          headers: {
            token: token
          }
        }).then(function (r) {
          if (r.data.success) {
            store.commit('loadEntData', r.data.detail)
            next('/user/home')
          } else {
          // 错误 token 则清除
            store.commit('logout')
            next()
          }
        })
      }
    } else if (token === null || token === '') {
    // 没有 token 跳转到登录界面
      next('/user/login')
    } else {
      if (to.path.startsWith('/user/')) {
      // 缓存数据类型
        if (localStorage.getItem('trace-type-list') === null) {
          axios.get('/api/ent/SelectAllType', {
            headers: {
              token: token
            }
          }).then(function (r) {
            if (r.data.success) {
              localStorage.setItem('trace-type-list', pako.deflate(JSON.stringify(r.data.detail)).toString())
            }
          })
        }
        // 同步时间
        store.commit('setServerTimeLoading', 1)

        const t = localStorage.getItem('trace-server-time')
        const last = localStorage.getItem('trace-last-time')
        const cuur = ~~(Date.now() / 1000)

        if (last === null || last === '' || cuur - last > 600) {
        // 没有同步或距离上次同步超过十分钟
          axios.get('/api/ent/getTime', {
            headers: {
              token: token
            }
          }).then(function (r) {
            if (r.data.success) {
              localStorage.setItem('trace-server-time', r.data.detail)
              localStorage.setItem('trace-last-time', cuur)
              store.commit('setServerTime', r.data.detail)
              store.commit('setServerTimeLoading', 0)
            } else {
            // 可能错误 token 重新登录
              alert('账号验证失败，请重新登录')
              store.commit('logout')
              next('/user/login')
            }
          }).catch(function (r) {
            store.commit('setServerTimeLoading', 2)
          })
          next()
        } else {
        // 10 分钟未过 使用缓存
          store.commit('setServerTime', t)
          store.commit('setServerTimeLoading', 0)
          next()
        }
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  const title = []
  if (to.meta.title) {
    title.push(to.meta.title)
  }
  if (store.state.ent.ename) {
    title.push(store.state.ent.ename)
  }
  title.push('肉类溯源系统')
  document.title = title.join('-')
})

export default router
